<template>
  <e-panel v-bind="opts">
    <e-table ref="tableRef" v-bind="opts.commProps.tableProps" :actions="rowActions">
      <template ##name="row">
        <icon v-if="row.icon" :icon-name="row.icon" style="margin-right: 4px"></icon>
        <n-tag v-if="row.menuType === 3" :bordered="false" :type="btnClass(row.perms)" size="small">{{ row.name }}</n-tag>
        <template v-else>{{ row.name }}</template>
      </template>
    </e-table>
  </e-panel>
</template>

<script lang="ts" setup>
  import Model from './model'
  import { usePanel } from '@/components/ext'
  import { FormTypeEnum } from 'easy-descriptor'
  import { ButtonActions } from '@/components/ActionButton/commonActions'

  defineOptions({
    name: 'SysPermissionList'
  })

  const opts = usePanel(Model, { formProps: { cols: 2 } })

  const { tableRef } = opts.refs

  const handleAddChild = ({ row }: { row: Model }) => {
    opts.refs.formRef.value?.open(FormTypeEnum.ADD, {
      parentId: row.id,
      perms: `${row.perms}-`,
      menuType: (row.menuType ?? 0) + 1,
      sortNo: (row.children?.length ?? 0) + 1
    })
  }

  const btnClass = computed(() => (perms?: string | boolean) => {
    if (!perms || typeof perms === 'boolean') {
      return 'info'
    }
    if (perms.endsWith('delete')) {
      return 'error'
    }
    if (perms.endsWith('update')) {
      return 'warning'
    }
    if (perms.endsWith('insert')) {
      return 'primary'
    }
    return 'info'
  })

  const rowActions = (row: Model): ButtonActions => {
    return row.menuType !== 3
      ? [
          {
            action: 'addChild',
            html: '添加',
            text: true,
            type: 'primary',
            perms: 'insert',
            handle: handleAddChild
          },
          'edit',
          'delete'
        ]
      : ['edit', 'delete']
  }
</script>

<style scoped lang="less">
  .permission-name {
    display: flex;
    align-items: center;
    justify-content: start;
  }
</style>
